package sport;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Date;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import sport.media.BellFactory;

/**
 *
 * @author 7904112B
 */
public class Settings {
    public int       DELAY;
    public boolean   FLASH;
    public boolean   VIBRATE;
    public int       BELL;
    public Date     WORK;
    public Date     REST;
    public int      LAPS;
    
    Settings()    {  
        Load();  
    }
    
    public void Load()
    {
        try {
            RecordStore rs = RecordStore.openRecordStore("beep_settings", false);
            ByteArrayInputStream bin = new ByteArrayInputStream(rs.getRecord(1));
            DataInputStream din = new DataInputStream(bin);
            DELAY = din.readInt();
            FLASH = din.readBoolean();
            VIBRATE = din.readBoolean();
            BELL = din.readInt();
            WORK = new Date(din.readLong());
            REST = new Date(din.readLong());
            LAPS = din.readInt();
            bin.close();
            din.close();
            rs.closeRecordStore();
            bin = null; din = null; rs = null;
        } catch (Exception ex) {
            ex.printStackTrace();
            ex = null;
            DELAY   = 0;
            FLASH   = true ;
            VIBRATE = false;
            BELL    = BellFactory.MMAPIBell;
            WORK    = new Date(30000);
            REST    = new Date(30000);
            LAPS    = 3;
            Save();
        } 

    }
    public void Save()
    {
            RecordStore rs=null;
        ByteArrayOutputStream bout=null;
        try {
            bout = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(bout);
            dout.writeInt(DELAY);
            dout.writeBoolean(FLASH);
            dout.writeBoolean(VIBRATE);
            dout.writeInt(BELL);
            dout.writeLong(WORK.getTime());
            dout.writeLong(REST.getTime());
            dout.writeInt(LAPS);

            rs = RecordStore.openRecordStore("beep_settings", true);
            try
            {
                rs.setRecord(1,bout.toByteArray(), 0, bout.size());
            } catch (InvalidRecordIDException ire){
                //first run : create
                rs.addRecord(bout.toByteArray(), 0, bout.size());
                ire=null;    
            }
            
            rs.closeRecordStore();
            dout.close();
            bout.close();
    
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
